import { ref, computed } from "vue";
import { defineStore } from "pinia";
import { login } from "../api/login";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { getmenu } from "../api/menu";
import {getList} from "../api/user"
export const useUserStore = defineStore(
  "user",
  () => {
    const userInfo = ref({});
    const userData = ref({});
    const menuList = ref({});
    const router = useRouter();
    const getUserInfo = async (userData) => {
      const res = await login(userData);
      userInfo.value = res.data;
      if (res.code === 200) {
        ElMessage.success({ type: "success", message: "登录成功" });
        localStorage.setItem("Authorization", res.data.access_token);
        // 获取菜单列表
        const getMenuList = async () => {
          try {
            const response = await getmenu();
            const data = response.data;
            localStorage.setItem("menuList", JSON.stringify(data));
            menuList.value = data;
          } catch (error) {
            console.error(error);
          }
        };
        getMenuList();
        // 根据用户id查询用户信息
        const getUserInfo = async () => {
          try{
            const UserRes = await getList(userInfo.value.userId)
            localStorage.setItem("userDate", JSON.stringify(UserRes.data))
            userData.value = UserRes.data;
          }catch (error) {
            console.error(error);
          }
        }
        getUserInfo();
        router.push("/home");
      } else {
        ElMessage.error({ type: "error", message: "登录失败,账号或密码错误" });
      }
    };
    const cleraUserInfo = () => {
      localStorage.removeItem("Authorization");
    };

    return { getUserInfo, userInfo, cleraUserInfo, menuList,userData };
  },
  {
    persist: true,
  }
);

export const isCollapseStore = defineStore("isCollapse", () => {
  let isCollapse = ref(false);
  const updata = ()=>{
    isCollapse.value = !isCollapse.value;
  }
  return { isCollapse,updata};
});
